<?php

//模拟的控制器
class Controller {
    public static function index($request) {
        echo '控制器方法体',$request,'<br>';
    }
}

//中间件
class Before1 {
    public static function handle($request, Closure $next) {
        echo 'before1<br>';  //业务逻辑，注意前置与后置中间件业务逻辑代码的位置
        return $next($request);
    }
}

//中间件
class Before2 {
    public static function handle($request, Closure $next) {
        echo 'before2<br>';
        return $next($request);
    }
}

//中间件
class After1 {
    public static function handle($request, Closure $next) {
        $response = $next($request);
        echo 'after1<br>'; //业务逻辑，注意前置与后置中间件业务逻辑代码的位置
        return $response;
    }
}

//中间件
class After2 {
    public static function handle($request, Closure $next) {
        $response = $next($request);
        echo 'after2<br>';
        return $response;
    }
}

class Middleware {

    public static $queue;  //中间件队列
    public static function init() {        
        //模拟的中间件，数量任意添加
        self::$queue[] = [[After1::class,  'handle'], null];
        self::$queue[] = [[After2::class,  'handle'], null];
        self::$queue[] = [[Before1::class, 'handle'], null];
        self::$queue[] = [[Before2::class, 'handle'], null];
         //模拟的控制器
        self::$queue[] = [[Controller::class,  'index'], null];
    }
    
    //调用中间件
    public static function dispatch($request) {
        call_user_func(self::resolve(), $request);
    }
    
    //返回闭包函数,递归。
    public static function resolve() {

        return function($request) {
            $middleware = array_shift(self::$queue);
            if ($middleware != null) {
                list($call, $param) = $middleware;
                call_user_func_array($call, [$request, self::resolve()]);  //执行中间件
            }
        };
    }

}

$request = "模拟的request对象";
Middleware::init();
Middleware::dispatch($request);

?>